package edu.manju.mimi.charge.controller;

import edu.manju.mimi.core.R;
import edu.manju.mimi.core.security.JwtService;
import edu.manju.mimi.core.security.RedisService;
import edu.manju.mimi.core.utils.IpUtil;
import edu.manju.mimi.core.wxlogin.*;
import edu.manju.mimi.db.entity.User;
import edu.manju.mimi.db.service.IUserService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;

/**
 * <h4>mimi-charge</h4>
 * <p>咪咪充电用户登录控制器</p>
 *
 * @author : Lebei(lebei163@163.com)
 * @date : 2023-05-06 16:04
 **/
@RestController
@RequestMapping("/login")
public class LoginController {
    @Autowired
    private IUserService userService;

    @Autowired
    private JwtService jwtService;

    @Autowired
    private RedisService redisService;

    @Value("${wxmini.appid}")
    private String appid;

    @Value("${wxmini.secret}")
    private String secret;

    @PostMapping("/login")
    public R<LoginResponse> login(@RequestBody LoginInfo loginInfo, HttpServletRequest request) {
        String code = loginInfo.getCode();
        UserInfo userInfo = loginInfo.getUserInfo();
        if (code == null || userInfo == null) {
            return R.fail("bad parameters");
        }

        String openid = null;
        String sessionKey = null;
        try {
            String json = Code2SessionHelper.fetchJsonString(appid, secret, code);
            Code2Session code2Session = Code2Session.fromJson(json);
            openid = code2Session.getOpenid();
            sessionKey = code2Session.getSessionKey();
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (sessionKey == null || openid == null) {
            return R.fail("Code2session failed!");
        }

        User user = userService.selectByOpenId(openid);
        if (user == null) {
            // first time login: create a user
            user = new User();
            user.setUsername(openid);
            user.setPassword(openid);
            user.setOpenid(openid);
            user.setAvatar(userInfo.getAvatarUrl());
            user.setNickname(userInfo.getNickName());
            user.setGender(userInfo.getGender());
            user.setStatus((byte) 0);
            user.setLastLoginTime(LocalDateTime.now());
            user.setLastLoginIp(IpUtil.getIpAddr(request));
            user.setSessionKey(sessionKey);

            userService.save(user);
        } else {
            user.setLastLoginTime(LocalDateTime.now());
            user.setLastLoginIp(IpUtil.getIpAddr(request));
            user.setSessionKey(sessionKey);

            if (!userService.updateById(user)) {
                return R.updatedDataFailed();
            }
        }

        // token sign and save
        Integer userId = user.getId();
        String token = jwtService.sign(userId);
        redisService.set(token, userId.toString());

        // return login-response
        LoginResponse response = new LoginResponse();
        response.setToken(token);
        response.setUserInfo(userInfo);
        return R.ok(response);
    }
}
